<template>
  <div class="permit-apply">
    <div class="page-container">
      <!-- 页面头部 -->
      <div class="page-header">
        <h2>冷工工作许可证申请</h2>
        <div class="header-info">
          <el-tag type="info">许可证编号：{{ formData.permitNumber }}</el-tag>
          <el-tag type="warning" v-if="hasConflict">检测到时间/地点冲突</el-tag>
        </div>
      </div>
      
      <!-- 步骤条 -->
      <el-steps :active="currentStep" finish-status="success" align-center class="steps-container">
        <el-step title="JSA选择" description="选择关联的JSA" />
        <el-step title="基础信息" description="对应纸质版第1部分" />
        <el-step title="人员与证书" description="对应纸质版第2部分" />
        <el-step title="安全措施" description="对应纸质版第3部分" />
        <el-step title="风险控制证" description="危险辨识与风险控制" />
        <el-step title="审批提交" description="对应纸质版第5、6部分" />
      </el-steps>
      
      <!-- 表单内容 -->
      <div class="form-container">
        <!-- 步骤1：JSA选择 -->
        <div v-show="currentStep === 0" class="step-content">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>JSA选择</span>
                <el-tag type="info">选择关联的JSA</el-tag>
              </div>
            </template>
            
            <!-- JSA搜索和选择 -->
            <div class="jsa-selection-section">
              <el-form :model="jsaSelectionForm" :rules="jsaSelectionRules" ref="jsaSelectionFormRef" label-width="120px">
                <el-form-item label="搜索JSA" prop="searchKeyword">
                  <el-input
                    v-model="jsaSelectionForm.searchKeyword"
                    placeholder="请输入JSA编号、任务描述或工作位置进行搜索"
                    @input="searchJSAs"
                    clearable
                  >
                    <template #append>
                      <el-button @click="searchJSAs">
                        <el-icon><Search /></el-icon>
                        搜索
                      </el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </el-form>
              
              <!-- JSA列表 -->
              <div class="jsa-list">
                <h4>可选择的JSA列表</h4>
                <el-table
                  :data="jsaOptions"
                  @row-click="selectJSA"
                  highlight-current-row
                  style="width: 100%"
                  max-height="400"
                >
                  <el-table-column prop="jsaNumber" label="JSA编号" width="180" />
                  <el-table-column prop="jobDescription" label="任务描述" min-width="200" />
                  <el-table-column prop="workPosition" label="工作位置" width="150" />
                  <el-table-column prop="analysisUnit" label="分析单位" width="150" />
                  <el-table-column prop="personInCharge" label="工作负责人" width="120" />
                  <el-table-column prop="createTime" label="创建时间" width="150" />
                  <el-table-column label="操作" width="100">
                    <template #default="{ row }">
                      <el-button type="primary" size="small" @click="selectJSA(row)">
                        选择
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              
              <!-- 已选择的JSA信息 -->
              <div v-if="selectedJSA" class="selected-jsa-info">
                <h4>已选择的JSA信息</h4>
                <el-card class="jsa-info-card">
                  <el-descriptions :column="2" border>
                    <el-descriptions-item label="JSA编号">{{ selectedJSA.jsaNumber }}</el-descriptions-item>
                    <el-descriptions-item label="任务描述">{{ selectedJSA.jobDescription }}</el-descriptions-item>
                    <el-descriptions-item label="工作位置">{{ selectedJSA.workPosition }}</el-descriptions-item>
                    <el-descriptions-item label="分析单位">{{ selectedJSA.analysisUnit }}</el-descriptions-item>
                    <el-descriptions-item label="工作负责人">{{ selectedJSA.personInCharge }}</el-descriptions-item>
                    <el-descriptions-item label="创建时间">{{ selectedJSA.createTime }}</el-descriptions-item>
                    <el-descriptions-item label="参加分析人员" :span="2">
                      <el-tag
                        v-for="person in selectedJSA.personsAnalyzedJob"
                        :key="person"
                        style="margin-right: 8px; margin-bottom: 4px"
                      >
                        {{ person }}
                      </el-tag>
                    </el-descriptions-item>
                  </el-descriptions>
                  
                  <!-- JSA分析表预览 -->
                  <div v-if="selectedJSA.analysisData" class="jsa-analysis-preview">
                    <h5>JSA分析表预览</h5>
                    <el-table :data="selectedJSA.analysisData.workSteps" border size="small">
                      <el-table-column prop="sequence" label="序号" width="60" />
                      <el-table-column prop="stepName" label="工作步骤" />
                    </el-table>
                  </div>
                </el-card>
              </div>
            </div>
          </el-card>
        </div>
        
        <!-- 步骤2：基础信息（对应纸质版第1部分） -->
        <div v-show="currentStep === 1" class="step-content">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>工作许可证申请</span>
                <el-tag type="info">对应纸质版第1部分</el-tag>
              </div>
            </template>
            <el-form :model="formData" :rules="basicInfoRules" ref="basicInfoForm" label-width="120px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="许可证编号" prop="permitNumber">
                    <el-input v-model="formData.permitNumber" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="申请人" prop="applicant">
                    <el-input v-model="formData.applicant" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-form-item label="工作地点" prop="location">
                <el-input v-model="formData.location" placeholder="请输入工作地点">
                  <template #append>
                    <el-button @click="selectLocationOnMap">选择地图</el-button>
                  </template>
                </el-input>
              </el-form-item>
              
              <el-form-item label="作业等级" prop="workLevel">
                <el-radio-group v-model="formData.workLevel">
                  <el-radio value="level1">一级</el-radio>
                  <el-radio value="level2">二级</el-radio>
                  <el-radio value="level3">三级</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="工作描述" prop="workDescription">
                <el-input
                  v-model="formData.workDescription"
                  type="textarea"
                  :rows="4"
                  placeholder="请详细描述工作内容（可另附文件）"
                />
                <div class="form-tip">
                  <el-button type="text" @click="uploadAttachment">上传附件</el-button>
                </div>
              </el-form-item>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="计划开始时间" prop="startTime">
                    <el-date-picker
                      v-model="formData.startTime"
                      type="datetime"
                      placeholder="选择开始时间"
                      format="YYYY-MM-DD HH:mm"
                      value-format="YYYY-MM-DD HH:mm"
                      @change="checkTimeConflict"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="计划结束时间" prop="endTime">
                    <el-date-picker
                      v-model="formData.endTime"
                      type="datetime"
                      placeholder="选择结束时间"
                      format="YYYY-MM-DD HH:mm"
                      value-format="YYYY-MM-DD HH:mm"
                      @change="checkTimeConflict"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-alert
                title="工作许可证有效期最长为12小时或至本班结束"
                type="info"
                :closable="false"
                style="margin-top: 10px"
              />
              
              <!-- 冲突提示 -->
              <el-alert
                v-if="hasConflict"
                title="检测到冲突"
                type="warning"
                :description="conflictMessage"
                show-icon
                :closable="false"
                style="margin-top: 10px"
              />
            </el-form>
          </el-card>
        </div>
        
        <!-- 步骤3：人员与证书（对应纸质版第2部分） -->
        <div v-show="currentStep === 2" class="step-content">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>特殊作业证书</span>
                <el-tag type="info">对应纸质版第2部分</el-tag>
              </div>
            </template>
            
            <!-- 特种作业人员表格 -->
            <div class="personnel-section">
              <div class="section-header">
                <h4>特种作业人员</h4>
                <el-button type="primary" @click="showPersonnelDialog = true">
                  <el-icon><Plus /></el-icon>
                  添加人员
                </el-button>
              </div>
              
              <el-table :data="formData.specialPersonnel" border style="margin-top: 16px">
                <el-table-column prop="name" label="姓名" width="120" />
                <el-table-column prop="certificateNumber" label="证书编号" width="150" />
                <el-table-column prop="certificateName" label="证件名称" width="150" />
                <el-table-column prop="validityPeriod" label="有效期" width="120" />
                <el-table-column label="状态" width="100">
                  <template #default="{ row }">
                    <el-tag :type="isCertificateValid(row.validityPeriod) ? 'success' : 'danger'">
                      {{ isCertificateValid(row.validityPeriod) ? '有效' : '已过期' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100">
                  <template #default="{ row, $index }">
                    <el-button type="text" @click="removeSpecialPersonnel($index)">移除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            
            <el-divider />
            
            <!-- 现场监护人和工作负责人 -->
            <div class="supervisor-section">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="现场监护人" prop="onSiteSupervisor">
                    <el-select v-model="formData.onSiteSupervisor" placeholder="从人员库选择" filterable>
                      <el-option
                        v-for="person in personnelOptions"
                        :key="person.id"
                        :label="person.name"
                        :value="person.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="工作负责人" prop="workLeader">
                    <el-select v-model="formData.workLeader" placeholder="从人员库选择" filterable>
                      <el-option
                        v-for="person in personnelOptions"
                        :key="person.id"
                        :label="person.name"
                        :value="person.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-card>
        </div>
        
        <!-- 步骤4：安全措施（对应纸质版第3部分） -->
        <div v-show="currentStep === 3" class="step-content">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>预防措施</span>
                <el-tag type="info">对应纸质版第3部分</el-tag>
              </div>
            </template>
            
            <!-- 个人防护装备（PPE） -->
            <div class="ppe-section">
              <h4>个人防护装备（PPE）</h4>
              <el-checkbox-group v-model="formData.ppeItems">
                <el-row :gutter="10">
                  <el-col :span="8" v-for="item in ppeOptions" :key="item.id">
                    <el-checkbox :label="item.id">{{ item.name }}</el-checkbox>
                  </el-col>
                </el-row>
              </el-checkbox-group>
              
              <!-- 其他PPE -->
              <div v-if="formData.ppeItems.includes('other')" class="other-ppe">
                <el-input
                  v-model="formData.otherPpe"
                  placeholder="请输入其他个人防护装备"
                  style="margin-top: 10px"
                />
              </div>
            </div>
            
            <el-divider />
            
            <!-- 其它安全措施 -->
            <div class="other-safety-section">
              <h4>其它安全措施</h4>
              <el-input
                v-model="formData.otherSafetyMeasures"
                type="textarea"
                :rows="3"
                placeholder="采取的其它安全措施（如果需要）"
              />
            </div>
            
            <el-divider />
            
            <!-- 气体检测方案 -->
            <div class="gas-detection-section">
              <h4>气体检测方案</h4>
              <el-radio-group v-model="formData.gasDetectionType" @change="onGasDetectionTypeChange">
                <el-radio value="intermittent">间歇</el-radio>
                <el-radio value="continuous">持续</el-radio>
                <el-radio value="not_applicable">不适用</el-radio>
              </el-radio-group>
              
              <!-- 检测频率输入 -->
              <div v-if="formData.gasDetectionType === 'intermittent' || formData.gasDetectionType === 'continuous'" class="detection-frequency">
                <el-input
                  v-model="formData.detectionFrequency"
                  placeholder="确定检测频率"
                  style="margin-top: 10px; width: 300px"
                />
              </div>
            </div>
            
            <el-divider />
            
            <!-- 气体检测记录表说明 -->
            <div class="gas-record-section">
              <h4>气体检测记录表</h4>
              <el-alert
                title="此表格将在作业执行过程中，由气测人员通过移动端填写。在最终打印的许可证上，会留出空白表格。"
                type="info"
                :closable="false"
              />
            </div>
          </el-card>
        </div>
        
        <!-- 步骤5：风险控制证（危险辨识与风险控制） -->
        <div v-show="currentStep === 4" class="step-content">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>风险控制证</span>
                <el-tag type="info">危险辨识与风险控制</el-tag>
              </div>
            </template>
            
            <!-- 危险辨识部分 -->
            <div class="hazard-identification-section">
              <h4>该工作是否包含危险辨识?(在对应方框中打√选择适用的风险)</h4>
              <div class="hazard-grid">
                <el-row :gutter="10">
                  <el-col :span="6" v-for="hazard in hazardOptions" :key="hazard.id">
                    <div class="hazard-item">
                      <el-checkbox v-model="formData.identifiedHazards" :label="hazard.id">
                        <div class="hazard-content">
                          <div class="hazard-icon">{{ hazard.icon }}</div>
                          <div class="hazard-name">{{ hazard.name }}</div>
                        </div>
                      </el-checkbox>
                    </div>
                  </el-col>
                </el-row>
              </div>
              
              <!-- 其他危险 -->
              <div class="other-hazard">
                <el-checkbox v-model="formData.identifiedHazards" label="other_hazard">
                  <span>其它危险:</span>
                  <el-input
                    v-model="formData.otherHazard"
                    placeholder="请描述其他危险"
                    style="width: 200px; margin-left: 10px"
                    v-if="formData.identifiedHazards.includes('other_hazard')"
                  />
                </el-checkbox>
              </div>
            </div>
            
            <el-divider />
            
            <!-- 风险控制部分 -->
            <div class="risk-control-section">
              <h4>风险控制:可以通过以下方法控制或减少识别出来的危险(在对应方框中打√选择控制方式)</h4>
              
              <!-- 工作许可 -->
              <div class="control-category">
                <h5>1. 工作许可 (Work Permit)</h5>
                <el-checkbox-group v-model="formData.workPermitControls">
                  <el-row :gutter="10">
                    <el-col :span="6" v-for="item in workPermitOptions" :key="item.id">
                      <el-checkbox :label="item.id">{{ item.name }}</el-checkbox>
                    </el-col>
                  </el-row>
                </el-checkbox-group>
              </div>
              
              <!-- 文件记录 -->
              <div class="control-category">
                <h5>2. 文件记录 (Document Records)</h5>
                <el-checkbox-group v-model="formData.documentControls">
                  <el-row :gutter="10">
                    <el-col :span="6" v-for="item in documentOptions" :key="item.id">
                      <el-checkbox :label="item.id">{{ item.name }}</el-checkbox>
                    </el-col>
                  </el-row>
                </el-checkbox-group>
              </div>
              
              <!-- 安全 -->
              <div class="control-category">
                <h5>3. 安全 (Safety)</h5>
                <el-checkbox-group v-model="formData.safetyControls">
                  <el-row :gutter="10">
                    <el-col :span="6" v-for="item in safetyOptions" :key="item.id">
                      <el-checkbox :label="item.id">{{ item.name }}</el-checkbox>
                    </el-col>
                  </el-row>
                </el-checkbox-group>
              </div>
              
              <!-- 环境 -->
              <div class="control-category">
                <h5>4. 环境 (Environment)</h5>
                <el-checkbox-group v-model="formData.environmentControls">
                  <el-row :gutter="10">
                    <el-col :span="6" v-for="item in environmentOptions" :key="item.id">
                      <el-checkbox :label="item.id">{{ item.name }}</el-checkbox>
                    </el-col>
                  </el-row>
                </el-checkbox-group>
              </div>
              
              <!-- 劳动用品 -->
              <div class="control-category">
                <h5>5. 劳动用品 (Labor Protection Articles/PPE)</h5>
                <el-checkbox-group v-model="formData.ppeControls">
                  <el-row :gutter="10">
                    <el-col :span="6" v-for="item in ppeControlOptions" :key="item.id">
                      <el-checkbox :label="item.id">{{ item.name }}</el-checkbox>
                    </el-col>
                  </el-row>
                </el-checkbox-group>
              </div>
              
              <!-- 设备 -->
              <div class="control-category">
                <h5>6. 设备 (Equipment)</h5>
                <el-checkbox-group v-model="formData.equipmentControls">
                  <el-row :gutter="10">
                    <el-col :span="6" v-for="item in equipmentOptions" :key="item.id">
                      <el-checkbox :label="item.id">{{ item.name }}</el-checkbox>
                    </el-col>
                  </el-row>
                </el-checkbox-group>
              </div>
              
              <!-- 手动工具 -->
              <div class="control-category">
                <h5>7. 手动工具 (Hand Tools)</h5>
                <el-checkbox-group v-model="formData.handToolControls">
                  <el-row :gutter="10">
                    <el-col :span="6" v-for="item in handToolOptions" :key="item.id">
                      <el-checkbox :label="item.id">{{ item.name }}</el-checkbox>
                    </el-col>
                  </el-row>
                </el-checkbox-group>
              </div>
              
              <!-- 敲击工具 -->
              <div class="control-category">
                <h5>8. 敲击工具 (Impact Tools)</h5>
                <el-checkbox-group v-model="formData.impactToolControls">
                  <el-row :gutter="10">
                    <el-col :span="6" v-for="item in impactToolOptions" :key="item.id">
                      <el-checkbox :label="item.id">{{ item.name }}</el-checkbox>
                    </el-col>
                  </el-row>
                </el-checkbox-group>
              </div>
              
              <!-- 手持动力工具 -->
              <div class="control-category">
                <h5>9. 手持动力工具 (Handheld Power Tools)</h5>
                <el-checkbox-group v-model="formData.powerToolControls">
                  <el-row :gutter="10">
                    <el-col :span="6" v-for="item in powerToolOptions" :key="item.id">
                      <el-checkbox :label="item.id">{{ item.name }}</el-checkbox>
                    </el-col>
                  </el-row>
                </el-checkbox-group>
              </div>
              
              <!-- 热工 -->
              <div class="control-category">
                <h5>10. 热工 (Hot Work)</h5>
                <el-checkbox-group v-model="formData.hotWorkControls">
                  <el-row :gutter="10">
                    <el-col :span="6" v-for="item in hotWorkOptions" :key="item.id">
                      <el-checkbox :label="item.id">{{ item.name }}</el-checkbox>
                    </el-col>
                  </el-row>
                </el-checkbox-group>
              </div>
              
              <!-- 搬运/吊装 -->
              <div class="control-category">
                <h5>11. 搬运/吊装 (Handling/Lifting)</h5>
                <el-checkbox-group v-model="formData.liftingControls">
                  <el-row :gutter="10">
                    <el-col :span="6" v-for="item in liftingOptions" :key="item.id">
                      <el-checkbox :label="item.id">{{ item.name }}</el-checkbox>
                    </el-col>
                  </el-row>
                </el-checkbox-group>
              </div>
              
              <!-- 其他 -->
              <div class="control-category">
                <h5>12. 其他 (Other)</h5>
                <el-checkbox-group v-model="formData.otherControls">
                  <el-row :gutter="10">
                    <el-col :span="6" v-for="item in otherControlOptions" :key="item.id">
                      <el-checkbox :label="item.id">{{ item.name }}</el-checkbox>
                    </el-col>
                  </el-row>
                </el-checkbox-group>
              </div>
            </div>
          </el-card>
        </div>
        
        <!-- 步骤6：审批流程与提交（对应纸质版第5、6部分） -->
        <div v-show="currentStep === 5" class="step-content">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>审批流程与提交</span>
                <el-tag type="info">对应纸质版第5、6部分</el-tag>
              </div>
            </template>
            
            <!-- 审批流程 -->
            <div class="approval-flow-section">
              <div class="section-header">
                <h4>审批流程</h4>
                <el-button type="text" @click="showApprovalFlowDialog = true">调整审批流程</el-button>
              </div>
              
              <div class="approval-steps">
                <el-steps direction="vertical" :active="0">
                  <el-step
                    v-for="(step, index) in formData.approvalFlow"
                    :key="index"
                    :title="step.role"
                    :description="`${step.person} (${step.department})`"
                  />
                </el-steps>
              </div>
            </div>
            
            <el-divider />
            
            <!-- 申请信息确认 -->
            <div class="confirmation-section">
              <h4>申请信息确认</h4>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="许可证编号">{{ formData.permitNumber }}</el-descriptions-item>
                <el-descriptions-item label="申请人">{{ formData.applicant }}</el-descriptions-item>
                <el-descriptions-item label="工作地点">{{ formData.location }}</el-descriptions-item>
                <el-descriptions-item label="作业等级">{{ getWorkLevelLabel(formData.workLevel) }}</el-descriptions-item>
                <el-descriptions-item label="开始时间">{{ formData.startTime }}</el-descriptions-item>
                <el-descriptions-item label="结束时间">{{ formData.endTime }}</el-descriptions-item>
                <el-descriptions-item label="现场监护人">{{ getPersonName(formData.onSiteSupervisor) }}</el-descriptions-item>
                <el-descriptions-item label="工作负责人">{{ getPersonName(formData.workLeader) }}</el-descriptions-item>
              </el-descriptions>
            </div>
            
            <div class="submit-section">
              <el-button type="primary" size="large" @click="submitApplication" :loading="submitting">
                <el-icon><Check /></el-icon>
                提交申请
              </el-button>
            </div>
          </el-card>
        </div>
      </div>
      
      <!-- 操作按钮 -->
      <div class="form-actions">
        <el-button v-if="currentStep > 0" @click="prevStep">上一步</el-button>
        <el-button v-if="currentStep < 5" type="primary" @click="nextStep">下一步</el-button>
      </div>
    </div>
    
    <!-- 人员选择对话框 -->
    <PersonnelSelectDialog
      v-model="showPersonnelDialog"
      @confirm="handlePersonnelSelected"
    />
    
    <!-- 审批流程调整对话框 -->
    <el-dialog v-model="showApprovalFlowDialog" title="调整审批流程" width="800px">
      <div class="approval-flow-editor">
        <el-button type="primary" @click="addApprover">添加审批人</el-button>
        <el-table :data="formData.approvalFlow" style="margin-top: 20px">
          <el-table-column prop="role" label="角色" width="150">
            <template #default="{ row, $index }">
              <el-select v-model="row.role" placeholder="选择角色">
                <el-option label="安全监督/兼职安全员" value="safety_supervisor" />
                <el-option label="区域负责人和监督人" value="area_manager" />
                <el-option label="批准人" value="approver" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="person" label="姓名" width="150">
            <template #default="{ row, $index }">
              <el-select v-model="row.person" placeholder="选择人员" filterable>
                <el-option
                  v-for="person in personnelOptions"
                  :key="person.id"
                  :label="person.name"
                  :value="person.name"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="department" label="部门" width="150">
            <template #default="{ row, $index }">
              <el-input v-model="row.department" placeholder="输入部门" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="{ row, $index }">
              <el-button type="text" @click="removeApprover($index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <el-button @click="showApprovalFlowDialog = false">取消</el-button>
        <el-button type="primary" @click="saveApprovalFlow">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import PersonnelSelectDialog from './components/PersonnelSelectDialog.vue'

const router = useRouter()
const userStore = useUserStore()

interface PermitFormData {
  permitNumber: string
  applicant: string
  location: string
  workLevel: string
  workDescription: string
  startTime: string
  endTime: string
  specialPersonnel: any[]
  onSiteSupervisor: string
  workLeader: string
  ppeItems: string[]
  otherPpe: string
  otherSafetyMeasures: string
  gasDetectionType: string
  detectionFrequency: string
  // JSA关联
  jsaId: string
  jsaNumber: string
  // 危险辨识
  identifiedHazards: string[]
  otherHazard: string
  // 风险控制
  workPermitControls: string[]
  documentControls: string[]
  safetyControls: string[]
  environmentControls: string[]
  ppeControls: string[]
  equipmentControls: string[]
  handToolControls: string[]
  impactToolControls: string[]
  powerToolControls: string[]
  hotWorkControls: string[]
  liftingControls: string[]
  otherControls: string[]
  approvalFlow: any[]
}

const currentStep = ref(0)
const submitting = ref(false)
const hasConflict = ref(false)
const conflictMessage = ref('')
const basicInfoForm = ref<FormInstance>()
const jsaSelectionFormRef = ref<FormInstance>()
const showPersonnelDialog = ref(false)
const showApprovalFlowDialog = ref(false)

// JSA选择相关数据
const jsaSelectionForm = reactive({
  searchKeyword: ''
})

const jsaSelectionRules: FormRules = {
  searchKeyword: [
    { required: false, message: '请输入搜索关键词', trigger: 'blur' }
  ]
}

// 选中的JSA
const selectedJSA = ref<any>(null)

// JSA选项列表
const jsaOptions = ref([
  {
    id: '1',
    jsaNumber: '2025-WELLTECH-TG-EM-001',
    jobDescription: '智能化项目 高空作业',
    workPosition: 'A区设备平台',
    analysisUnit: '维修部',
    personInCharge: '张三',
    personsAnalyzedJob: ['张三', '李四', '王五'],
    createTime: '2025-01-15 09:30',
    analysisData: {
      workSteps: [
        { sequence: 1, stepName: '准备工具和设备' },
        { sequence: 2, stepName: '检查安全带和防护设备' },
        { sequence: 3, stepName: '搭建脚手架' },
        { sequence: 4, stepName: '进行高空作业' },
        { sequence: 5, stepName: '清理现场' }
      ]
    }
  },
  {
    id: '2',
    jsaNumber: '2025-WELLTECH-TG-EM-002',
    jobDescription: '管道维修作业',
    workPosition: 'B区管道走廊',
    analysisUnit: '维修部',
    personInCharge: '李四',
    personsAnalyzedJob: ['李四', '赵六'],
    createTime: '2025-01-15 14:20',
    analysisData: {
      workSteps: [
        { sequence: 1, stepName: '关闭相关阀门' },
        { sequence: 2, stepName: '排空管道内介质' },
        { sequence: 3, stepName: '拆卸损坏管道' },
        { sequence: 4, stepName: '安装新管道' },
        { sequence: 5, stepName: '测试管道密封性' }
      ]
    }
  },
  {
    id: '3',
    jsaNumber: '2025-WELLTECH-TG-EM-003',
    jobDescription: '电气设备检修',
    workPosition: 'C区配电室',
    analysisUnit: '电气部',
    personInCharge: '王五',
    personsAnalyzedJob: ['王五', '张三'],
    createTime: '2025-01-16 08:15',
    analysisData: {
      workSteps: [
        { sequence: 1, stepName: '断电并挂牌' },
        { sequence: 2, stepName: '验电确认' },
        { sequence: 3, stepName: '拆卸电气设备' },
        { sequence: 4, stepName: '检修设备' },
        { sequence: 5, stepName: '重新安装并测试' }
      ]
    }
  }
])

const formData = reactive<PermitFormData>({
  permitNumber: '',
  applicant: '',
  location: '',
  workLevel: '',
  workDescription: '',
  startTime: '',
  endTime: '',
  specialPersonnel: [],
  onSiteSupervisor: '',
  workLeader: '',
  ppeItems: [],
  otherPpe: '',
  otherSafetyMeasures: '',
  gasDetectionType: 'not_applicable',
  detectionFrequency: '',
  // JSA关联
  jsaId: '',
  jsaNumber: '',
  // 危险辨识
  identifiedHazards: [],
  otherHazard: '',
  // 风险控制
  workPermitControls: [],
  documentControls: [],
  safetyControls: [],
  environmentControls: [],
  ppeControls: [],
  equipmentControls: [],
  handToolControls: [],
  impactToolControls: [],
  powerToolControls: [],
  hotWorkControls: [],
  liftingControls: [],
  otherControls: [],
  approvalFlow: []
})

const basicInfoRules: FormRules = {
  location: [{ required: true, message: '请输入工作地点', trigger: 'blur' }],
  workLevel: [{ required: true, message: '请选择作业等级', trigger: 'change' }],
  workDescription: [{ required: true, message: '请输入工作描述', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
}

// PPE选项（对应纸质版）
const ppeOptions = [
  { id: 'work_clothes', name: '工服' },
  { id: 'safety_shoes', name: '劳保鞋' },
  { id: 'gloves', name: '手套' },
  { id: 'goggles', name: '护目镜' },
  { id: 'face_shield', name: '面罩' },
  { id: 'broadcast', name: '广播' },
  { id: 'earplugs', name: '耳塞' },
  { id: 'respirator', name: '呼吸器' },
  { id: 'full_body_harness', name: '全身式安全带' },
  { id: 'isolation_barrier', name: '标识/隔离屏障' },
  { id: 'lead_collar', name: '铅围脖' },
  { id: 'acid_proof_shoes', name: '防酸鞋' },
  { id: 'anti_static_device', name: '防静电装置' },
  { id: 'walkie_talkie', name: '对讲机' },
  { id: 'lead_glasses', name: '铅眼镜' },
  { id: 'radiation_detector', name: '放射性检查仪' },
  { id: 'acid_proof_clothing', name: '防酸服' },
  { id: 'radiation_protection', name: '放射源防护服' },
  { id: 'dosimeter', name: '剂量牌' },
  { id: 'rubber_gloves', name: '橡胶手套' },
  { id: 'other', name: '其他' }
]

// 人员选项（模拟数据）
const personnelOptions = [
  { id: '1', name: '张三', department: '生产部' },
  { id: '2', name: '李四', department: '安全部' },
  { id: '3', name: '王五', department: '维修部' },
  { id: '4', name: '赵六', department: '工程部' }
]

// 危险辨识选项
const hazardOptions = [
  { id: 'oil_gas_system', name: '油气系统', icon: '⛽' },
  { id: 'live_equipment', name: '带电设备/静电', icon: '⚡' },
  { id: 'insufficient_lighting', name: '照明不足', icon: '💡' },
  { id: 'insufficient_maintenance', name: '设备维护不够', icon: '🔧' },
  { id: 'pressurized_system', name: '带压系统', icon: '⚡' },
  { id: 'confined_space', name: '限制空间/入口受限', icon: '🚪' },
  { id: 'high_noise', name: '高噪音区域', icon: '🔊' },
  { id: 'critical_lifting', name: '关键吊装', icon: '🏗️' },
  { id: 'ignition_source', name: '点火源', icon: '🔥' },
  { id: 'weather_conditions', name: '天气状况', icon: '🌤️' },
  { id: 'toxic_gas', name: '有毒气体', icon: '☠️' },
  { id: 'manual_handling', name: '人工搬运', icon: '📦' },
  { id: 'flammable_gas', name: '可燃气体', icon: '🔥' },
  { id: 'work_at_height', name: '高处作业', icon: '🪜' },
  { id: 'procedures', name: '程序/工作指导书', icon: '📋' },
  { id: 'hand_tools', name: '手动工具', icon: '🔨' },
  { id: 'dust', name: '粉尘', icon: '💨' },
  { id: 'hot_cold_surface', name: '热/冷表面', icon: '🌡️' },
  { id: 'impact_tools', name: '敲击工具(如榔头)', icon: '🔨' },
  { id: 'power_tools', name: '手持动力工具', icon: '⚙️' },
  { id: 'chemicals_radiation', name: '化学品/天然放射物/辐射', icon: '☢️' },
  { id: 'slips_trips', name: '滑倒/绊倒', icon: '⚠️' },
  { id: 'sharp_objects', name: '尖锐物体', icon: '🔪' },
  { id: 'pinch_points', name: '夹挤点', icon: '🤏' },
  { id: 'conflicting_work', name: '交叉工作', icon: '👥' },
  { id: 'overhead_hazard', name: '头顶上方危险', icon: '⬇️' },
  { id: 'released_into_water', name: '释放到水中', icon: '💧' },
  { id: 'waste_classification', name: '废物分类', icon: '🗑️' },
  { id: 'waste_generation', name: '产生废物', icon: '♻️' }
]

// 工作许可选项
const workPermitOptions = [
  { id: 'hot_work_permit', name: '热工工作许可证' },
  { id: 'cold_work_permit', name: '冷工工作许可证' },
  { id: 'energy_isolation_permit', name: '能量隔离证' },
  { id: 'confined_space_permit', name: '限制空间准入证' },
  { id: 'other_permit', name: '其它' }
]

// 文件记录选项
const documentOptions = [
  { id: 'pre_job_inspection', name: '启动、作业前安全检查' },
  { id: 'joint_operations', name: '联合作业/交叉作业' },
  { id: 'maintenance_procedures', name: '维修程序' },
  { id: 'operating_procedures', name: '操作程序' },
  { id: 'job_safety_analysis', name: '工作分析' },
  { id: 'msds', name: '材料安全数据表 (MSDS)' },
  { id: 'electrical_diagram', name: '电气图/单线图' },
  { id: 'height_rescue_plan', name: '高空作业救援计划' },
  { id: 'other_document', name: '其它' }
]

// 安全选项
const safetyOptions = [
  { id: 'walkie_talkie', name: '对讲机' },
  { id: 'rescue_equipment', name: '救援设备' },
  { id: 'warning_tape', name: '警示带/孔洞盖' },
  { id: 'warning_signs', name: '警告标志' },
  { id: 'broadcast_notification', name: '广播通知' },
  { id: 'radiation_monitoring', name: '辐射监测' },
  { id: 'adequate_lighting', name: '充足的照明' },
  { id: 'other_safety', name: '其它' }
]

// 环境选项
const environmentOptions = [
  { id: 'weather_protection', name: '不良天气保护' },
  { id: 'spill_response', name: '泄露处理材料' },
  { id: 'special_waste', name: '特殊废物' },
  { id: 'area_cleaning', name: '区域清洁' },
  { id: 'floor_drain_covers', name: '覆盖地漏' },
  { id: 'waste_oil_generation', name: '产生废油' },
  { id: 'oil_contaminated', name: '含油沾染物' },
  { id: 'chemical_spraying', name: '化学品喷灌' },
  { id: 'other_environment', name: '其他' }
]

// PPE控制选项
const ppeControlOptions = [
  { id: 'regular_ppe', name: '常规PPE' },
  { id: 'high_voltage_ppe', name: '高电压PPE' },
  { id: 'personal_dosimeter', name: '个人剂量牌' },
  { id: 'portable_dosimeter', name: '便携式剂量表' },
  { id: 'rubber_gloves', name: '胶皮手套' },
  { id: 'face_shield', name: '面罩' },
  { id: 'safety_goggles', name: '护目镜' },
  { id: 'hearing_protection', name: '听力保护' },
  { id: 'fall_protection', name: '坠落保护' },
  { id: 'welding_mask', name: '焊接面罩' },
  { id: 'welding_gloves', name: '焊接手套' },
  { id: 'chemical_gloves', name: '防化手套' },
  { id: 'chemical_clothing', name: '防化服' },
  { id: 'dust_mask', name: '防尘口罩' },
  { id: 'scba', name: '自供气式呼吸器' },
  { id: 'reflective_vest', name: '反光背心' },
  { id: 'impact_gloves', name: '抗冲击手套' },
  { id: 'radiation_clothing', name: '辐射防护服' },
  { id: 'lead_glasses', name: '铅眼镜' },
  { id: 'lead_collar', name: '铅围脖' },
  { id: 'other_ppe_control', name: '其他' }
]

// 设备选项
const equipmentOptions = [
  { id: 'qualified_personnel', name: '有资质人员操作' },
  { id: 'correct_ppe', name: '确定并使用正确的PPE' }
]

// 手动工具选项
const handToolOptions = [
  { id: 'correct_type', name: '正确的类型' },
  { id: 'correct_size', name: '正确的尺寸' },
  { id: 'secured_falling', name: '进行固定以防止坠落' },
  { id: 'other_hand_tool', name: '其他' }
]

// 敲击工具选项
const impactToolOptions = [
  { id: 'inspect_handle_head', name: '检查手柄和头部' },
  { id: 'suitable_use', name: '适合使用' },
  { id: 'non_sparking', name: '不产生火花' },
  { id: 'other_impact_tool', name: '其他' }
]

// 手持动力工具选项
const powerToolOptions = [
  { id: 'inspect_air_lines', name: '检查气管线' },
  { id: 'anti_disconnect_chains', name: '使用软管连接防脱链' },
  { id: 'inspect_hydraulic_lines', name: '检查液压管线' },
  { id: 'inspect_connections', name: '检查连接处' },
  { id: 'inspect_cables', name: '检查电缆' },
  { id: 'hazardous_area_suitable', name: '适合在危险区域使用' },
  { id: 'other_power_tool', name: '其它' }
]

// 热工选项
const hotWorkOptions = [
  { id: 'fire_watcher', name: '看火人' },
  { id: 'fire_extinguisher', name: '灭火器' },
  { id: 'fire_blanket', name: '防火毯' },
  { id: 'control_spark_splash', name: '控制火花飞溅' },
  { id: 'grounding', name: '接地' },
  { id: 'two_person_system', name: '两人工作制' },
  { id: 'wetting_sprinkling', name: '湿润/洒水' },
  { id: 'other_hot_work', name: '其它' }
]

// 搬运/吊装选项
const liftingOptions = [
  { id: 'critical_lift_analysis', name: '关键吊装风险分析' },
  { id: 'equipment_certified', name: '设备有证书/适合该工作' },
  { id: 'full_body_harness', name: '全身式安全带' },
  { id: 'suitable_manual_handling', name: '适合的人工搬运方法' },
  { id: 'correct_color_coding', name: '正确的色标' },
  { id: 'certified_personnel', name: '经认证的人员' },
  { id: 'lifting_plan', name: '吊装计划' },
  { id: 'two_slingers', name: '两名司索人员' },
  { id: 'confirm_communication', name: '确认通讯方法' },
  { id: 'spotter_high_visibility', name: '指挥人员穿着高反光马甲' },
  { id: 'dedicated_personnel_equipment', name: '专用载人设备' },
  { id: 'temporary_red_zone', name: '临时红区' },
  { id: 'other_lifting', name: '其他' }
]

// 其他控制选项
const otherControlOptions = [
  { id: 'electric_heat_tracing', name: '电伴热隔离' },
  { id: 'insulation_removal', name: '拆除保温' },
  { id: 'correct_hand_placement', name: '手的正确位置' },
  { id: 'familiar_environment', name: '熟知环境' },
  { id: 'static_electricity_discharge', name: '静电释放' },
  { id: 'other_control_measures', name: '其它控制措施' }
]

// 生成许可证编号
const generatePermitNumber = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  return `L3.2-QHSE-P016-R04-WT-${year}${month}${day}${random}`
}

// 检查时间冲突
const checkTimeConflict = () => {
  if (formData.startTime && formData.endTime) {
    const start = new Date(formData.startTime)
    const end = new Date(formData.endTime)
    const diffHours = (end.getTime() - start.getTime()) / (1000 * 60 * 60)
    
    if (diffHours > 12) {
      hasConflict.value = true
      conflictMessage.value = '许可证有效期超过12小时限制'
    } else if (diffHours <= 0) {
      hasConflict.value = true
      conflictMessage.value = '结束时间必须晚于开始时间'
    } else {
      hasConflict.value = false
    }
  }
}

// 检查证书是否有效
const isCertificateValid = (validityPeriod: string) => {
  const today = new Date()
  const expiry = new Date(validityPeriod)
  return expiry > today
}

// 获取作业等级标签
const getWorkLevelLabel = (level: string) => {
  const levelMap = {
    level1: '一级',
    level2: '二级',
    level3: '三级'
  }
  return levelMap[level as keyof typeof levelMap] || level
}

// 获取人员姓名
const getPersonName = (personId: string) => {
  const person = personnelOptions.find(p => p.id === personId)
  return person ? person.name : ''
}

// 气体检测类型变化
const onGasDetectionTypeChange = () => {
  if (formData.gasDetectionType === 'not_applicable') {
    formData.detectionFrequency = ''
  }
}

// 搜索JSA
const searchJSAs = () => {
  // 这里可以实现实际的搜索逻辑
  // 目前只是简单的过滤
  if (jsaSelectionForm.searchKeyword) {
    // 模拟搜索逻辑
    ElMessage.info(`搜索关键词: ${jsaSelectionForm.searchKeyword}`)
  }
}

// 选择JSA
const selectJSA = (jsa: any) => {
  selectedJSA.value = jsa
  formData.jsaId = jsa.id
  formData.jsaNumber = jsa.jsaNumber
  
  // 自动填充一些基础信息
  formData.location = jsa.workPosition
  formData.workDescription = jsa.jobDescription
  
  ElMessage.success(`已选择JSA: ${jsa.jsaNumber}`)
}

// 下一步
const nextStep = async () => {
  // 第一步：JSA选择验证
  if (currentStep.value === 0) {
    if (!selectedJSA.value) {
      ElMessage.error('请先选择一个JSA')
      return
    }
  }
  
  // 第二步：基础信息验证
  if (currentStep.value === 1) {
    if (!basicInfoForm.value) return
    try {
      await basicInfoForm.value.validate()
    } catch {
      return
    }
  }
  
  if (currentStep.value < 5) {
    currentStep.value++
  }
}

// 上一步
const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

// 选择地图位置
const selectLocationOnMap = () => {
  ElMessage.info('地图选择功能开发中...')
}

// 上传附件
const uploadAttachment = () => {
  ElMessage.info('附件上传功能开发中...')
}

// 处理人员选择
const handlePersonnelSelected = (personnel: any[]) => {
  formData.specialPersonnel = [...formData.specialPersonnel, ...personnel]
}

// 移除特种作业人员
const removeSpecialPersonnel = (index: number) => {
  formData.specialPersonnel.splice(index, 1)
}

// 添加审批人
const addApprover = () => {
  formData.approvalFlow.push({
    role: '',
    person: '',
    department: ''
  })
}

// 移除审批人
const removeApprover = (index: number) => {
  formData.approvalFlow.splice(index, 1)
}

// 保存审批流程
const saveApprovalFlow = () => {
  showApprovalFlowDialog.value = false
  ElMessage.success('审批流程已更新')
}

// 提交申请
const submitApplication = async () => {
  try {
    submitting.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    ElMessage.success('许可证申请提交成功，已进入审批流程')
    router.push('/permit/list')
  } catch (error: any) {
    ElMessage.error(error.message || '提交失败')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  // 初始化表单数据
  formData.permitNumber = generatePermitNumber()
  formData.applicant = userStore.user?.nickname || '当前用户'
  
  // 初始化默认审批流程
  formData.approvalFlow = [
    { role: '安全监督/兼职安全员', person: '李四', department: '安全部' },
    { role: '区域负责人和监督人', person: '王五', department: '维修部' },
    { role: '批准人', person: '赵六', department: '工程部' }
  ]
})
</script>

<style lang="scss" scoped>
.permit-apply {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    
    h2 {
      color: #333;
      margin: 0;
    }
    
    .header-info {
      display: flex;
      gap: 12px;
    }
  }
  
  .steps-container {
    margin-bottom: 30px;
  }
  
  .form-container {
    .step-content {
      min-height: 500px;
    }
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .form-tip {
    margin-top: 8px;
  }
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    h4 {
      margin: 0;
      color: #333;
    }
  }
  
  .ppe-section {
    .other-ppe {
      margin-top: 10px;
    }
  }
  
  .detection-frequency {
    margin-top: 10px;
  }
  
  .approval-steps {
    margin-top: 16px;
  }
  
  .confirmation-section {
    margin-top: 20px;
  }
  
  .submit-section {
    text-align: center;
    margin-top: 30px;
  }
  
  .form-actions {
    text-align: center;
    margin-top: 30px;
    
    .el-button {
      margin: 0 8px;
    }
  }
  
  .approval-flow-editor {
    .el-button {
      margin-bottom: 16px;
    }
  }
  
  // 危险辨识样式
  .hazard-identification-section {
    .hazard-grid {
      margin-top: 16px;
    }
    
    .hazard-item {
      margin-bottom: 12px;
      
      .hazard-content {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .hazard-icon {
          font-size: 20px;
        }
        
        .hazard-name {
          font-size: 14px;
        }
      }
    }
    
    .other-hazard {
      margin-top: 16px;
      padding: 12px;
      background-color: #f5f7fa;
      border-radius: 4px;
    }
  }
  
  // 风险控制样式
  .risk-control-section {
    .control-category {
      margin-bottom: 24px;
      padding: 16px;
      border: 1px solid #e4e7ed;
      border-radius: 6px;
      background-color: #fafafa;
      
      h5 {
        margin: 0 0 12px 0;
        color: #303133;
        font-size: 16px;
        font-weight: 600;
      }
      
      .el-checkbox-group {
        .el-checkbox {
          margin-right: 16px;
          margin-bottom: 8px;
        }
      }
    }
  }
  
  // JSA选择样式
  .jsa-selection-section {
    .jsa-list {
      margin-top: 20px;
      
      h4 {
        color: #333;
        margin-bottom: 16px;
        font-size: 16px;
        font-weight: 600;
      }
      
      .el-table {
        .el-table__row {
          cursor: pointer;
          
          &:hover {
            background-color: #f5f7fa;
          }
        }
      }
    }
    
    .selected-jsa-info {
      margin-top: 24px;
      
      h4 {
        color: #333;
        margin-bottom: 16px;
        font-size: 16px;
        font-weight: 600;
      }
      
      .jsa-info-card {
        .el-descriptions {
          margin-bottom: 16px;
        }
        
        .jsa-analysis-preview {
          margin-top: 16px;
          
          h5 {
            color: #333;
            margin-bottom: 12px;
            font-size: 14px;
            font-weight: 600;
          }
        }
      }
    }
  }
}
</style>